/**
 * @Description:  temp
 * @author longfa liang
 * @date 2021/9/3
 */

var pu = require('../tool/public')
var temp_db = require('../db/temp')
var jurupdate = require('../tool/jurUpdate')

class temp {

    /*修改模板数据*/
    async update_temp_data (req, res, next) {
        let team_id = req.headers.team
        var temp_id = req.body.temp_id
        var _id = req.body._id
        var updateinfo = req.body.updateinfo

        let isnull = pu.isnull([team_id, temp_id, _id, updateinfo])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let tempinfo = await temp_db.findOne(temp_id, { _id: temp_db.ObjectID(_id) })

        var update = {}
        for (var obj in tempinfo) {

            for (var j = 0; j < updateinfo.length; j++) {
                if (obj == updateinfo[j].id) {
                    update[obj] = updateinfo[j].value
                }
            }
        }
        if (JSON.stringify(update) == '{}') {
            pu.fail('请填写修改内容', res)
        } else {

            await temp_db.updateOne(temp_id, { _id: temp_db.ObjectID(_id) }, { $set: update })
            pu.success('OK', update, res)
        }
    }

    /*查询模板数据*/
    async find_temp_data (req, res, next) {
        console.log("开始查询模板数据")
        let team_id = req.headers.team
        var findinfo = req.body.findinfo // 查询内容 此处需要前端配置好 如or  {or:[{a:1},{b:1}]}
        var temp_id = req.body.temp_id
        var _id = req.body._id
        let isnull = pu.isnull([temp_id, team_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        findinfo.team_id = temp_db.ObjectID(team_id)
        let info = await temp_db.find(temp_id, findinfo)
        //全局权限
        console.log("开始输出模板数据")
        pu.success('OK', info, res)
    }

    /*新增模板数据*/
    async add_temp_data (req, res, next) {
        let team_id = req.headers.team
        var temp_id = req.body.temp_id
        var data = req.body.data //data{id:"" ,value:""}
        let isnull = pu.isnull([temp_id, data])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let tempinfo = await temp_db.findOne('template', { _id: temp_db.ObjectID(temp_id) })
        if (!tempinfo) {
            pu.fail('ID不正确', res)
            return
        }
        /*查询模板匹配 只允许模板中有的字段插入*/

        var insertdata = {
            temp_id: temp_db.ObjectID(temp_id),
            team_id: temp_db.ObjectID(team_id),
        }
        let selecedata = tempinfo.template
        for (var i = 0; i < selecedata.length; i++) {
            for (var j = 0; j < data.length; j++) {
                if (selecedata[i].id == data[j].id) {
                    insertdata[selecedata[i].id] = data[j].value
                }
            }
        }
        /*此处要分集合存放*/
        await temp_db.insertOne(temp_id, insertdata)
        pu.success('OK', insertdata, res)
    }

    /*删除数据*/
    async delete_temp_data (req, res, next) {
        var team = req.headers.team
        var _id = req.body._idList
        var temp_id = req.body.temp_id


        let isnull = pu.isnull([ _id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        if (typeof _id !== 'object') {

            pu.fail('参数不正确', res)
            return
        }

        var where = { '$or': [] }
        for (var i = 0; i < _id.length; i++) {
            where['$or'].push({ _id: temp_db.ObjectID(_id[i]) })

        }
        await temp_db.deleteAll('template',where)
        pu.success('OK', '', res)
    }

    /*修改数据模板*/
    async update_data_template (req, res, next) {
        var _id = req.body._id
        let team_id = req.headers.team
        var is_delete = req.body.is_delete
        var name = req.body.name
        var select = req.body.select
        var temp = req.body.temp
        let isnull = pu.isnull([_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let tempinfo = await temp_db.findOne('template', { _id: temp_db.ObjectID(_id) })
        var inserdata = {}

        if (is_delete || is_delete == 0) {
            inserdata.is_delete = is_delete
            if (is_delete == 1) { //禁用 禁用需要修改权限
                jurupdate.jurupdate(team_id, { id: _id, type: 'temp' }, tempinfo.modeule, 1, 0)
            }
        }
        if (name) {
            inserdata.name = name
        }
        if (select) {
            inserdata.select = select
        }
        if (temp) {
            inserdata.temp = temp
        }
        await temp_db.update('template', { _id: temp_db.ObjectID(_id) }, { $set: inserdata })


        pu.success('OK', inserdata, res)

        //修复修改控件名称联动权限控件名称

        var adopt = [];//未知
        var newteam = {
            name: name,
            server: 'temp',
            status: 0,
            url: _id,
            type: 'temp',
            adopt: adopt,
            field: tempinfo.template,
            jurlist: []
        }
        jurupdate.jurupdate(team_id, newteam, tempinfo.modeule,1) //修改公司权限
    }

    /*查询数据模板*/
    async find_temp (req, res, next) {
        let team_id = req.headers.team
        var _id = req.body._id
        var is_delete = req.body.is_delete
        var text = req.body.text
        if (_id) {
            pu.success('OK', await temp_db.findOne('template', { _id: temp_db.ObjectID(_id) }), res)
    return
}
        let where = {
            team_id: temp_db.ObjectID(team_id)
        }
        if (text) {
            where.name = { $regex: text }
        }
        if (is_delete || is_delete == 0) {
            where.is_delete = is_delete
        }
        pu.success('OK', await temp_db.find('template', where), res)
    }

    /*新增数据模板*/
    async add_temp (req, res, next) {
        let team_id = req.headers.team
        let userid = req.headers.uid
        let username = req.body.username
        var temp = req.body.temp
        var name = req.body.name
        var select = req.body.select
        var title = req.body.title
        var modeule = req.body.modeule
        var modeule_name = req.body.modeule_name
        var list = temp.list


        let department_ids = req.body.department_ids;//部门列表["id","id"]
        let uids = req.body.uids;//用户列表["id","id"]
        let role_ids = req.body.role_ids; //角色列表["id","id"]


        let isnull = pu.isnull([list, modeule, name, temp, username])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let info_name =  await temp_db.findOne('template', { name: name })
        if(info_name ){
            pu.fail('名称已存在', res)
            return
        }
        var field = []
        var adopt = []
        var template = []
        /*excel 导出数据模板在 tool/excel.js*/
        var excel = {}
        for (var i = 0; i < list.length; i++) {
            excel[list[i].id] = { name: list[i].compName, type: list[i].dataType }
            if (list[i].regex) { //有替换的值
                excel[list[i].id].regex = list[i].regex
            }
            template.push({ name: list[i].name, id: list[i].id, type: list[i].dataType })
            if (list[i].jur) {
                field.push({ name: list[i].name, id: list[i].id, status: 0 })
            } else {
                adopt.push(list[i].id)
            }
        }
        // 处理数据
        var newTitle = []
        for (var i = 0; i < title.length; i++) {
            newTitle[i] = {name:title[i].name,id:title[i].id,type:title[i].type}
        }
        var inserdata = {
            template: template,
            title: newTitle,
            team_id: temp_db.ObjectID(team_id),
            temp: temp,
            name: name,
            modeule: modeule,
            modeule_name: modeule_name,
            is_delete: 0,
            add_userid: temp_db.ObjectID(userid),
            add_username: username,
            excel: excel,
            select: select,
        }
        let info = await temp_db.insertOne('template', inserdata)
        inserdata._id = info.insertedId
        /*
        *  1 、新增模板
        *  2、新增模板列表
        *  3、新增全部权限
        * */
        var newteam = {
            name: name,
            server:info.insertedId,
            status: 0,
            url: info.insertedId,
            type: 'temp',
            adopt: adopt,
            field: field,
            jurlist: [
                { 'function': 'update_temp_data', name: '修改'+name+'数据', status: 1 },
                { 'function': 'find_temp_data', name: '查询'+name+'数据', status: 1 },
                { 'function': 'add_temp_data', name: '新增'+name+'数据', status: 1 },
                { 'function': 'delete_temp_data', name: '删除'+name+'数据', status: 1 }
            ]
        }
        jurupdate.jurupdate(team_id, newteam, modeule,0) //修改公司权限

        //先角色的人

        //在权限的人

        //控件用户权限 jurinfor 表 中字段即控件权限

        pu.success('OK', inserdata, res)
    }
    /* 添加控件表单 */
    async add_control_template(req, res, next){
        let team_id = req.headers.team
        let userid = req.headers.teamuser_id
        let username = req.body.username
        let createTime = req.body.createTime
        var controlTemp = req.body.controlTemp
        var name = req.body.name
        var icon = req.body.icon
        // var list = controlTemp.list
        // 要存入的数据
        var data = {
            team_id: temp_db.ObjectID(team_id),
            controlTemp: controlTemp,
            createTime: createTime,
            add_userid: temp_db.ObjectID(userid),
            name:name,
            username:username,
            icon:icon,
            status:0, // 0不启用，1启用
            is_delete:0//0不删除，1删除
        }
        let isnull = pu.isnull([controlTemp,username,name])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let info = await temp_db.insertOne('controlTemp', data)
        data._id= info.insertedId
        pu.success('OK',data, res)
        return
    }
    /*查询控件表单 */
    async find_control_template(req, res, next){
        let team_id = req.headers.team
        var name = req.body.name
        var _id = req.body._id
        var status = req.body.status
        var is_delete = req.body.is_delete
        var where = {
            team_id:temp_db.ObjectID(team_id)
        }

        if(_id){
            let tempinfo = await temp_db.findOne('controlTemp', { _id: temp_db.ObjectID(_id) })
            pu.success('OK',tempinfo, res)
            return
        }
        if(status||status===0){
            where.status=status
        }
        if(is_delete||is_delete===0){
            where.is_delete=is_delete
        }
        if(name){
            where.name={$regex:name}
        }
        let tempinfo = await temp_db.find('controlTemp',where)
        pu.success('OK',tempinfo, res)

    }
    // 修改表单控件
    async edit_control_template(req, res, next){
        // let team_id = req.headers.team
        // let userid = req.headers.teamuser_id
        // var temp_id = req.body.temp_id
        var data = req.body

        var where  = {}

        if(data.name){
            where.name = data.name
        }
        if(data.status || data.status === 0){
            where.status = data.status
        }
        if(data.is_delete || data.is_delete === 0){
            where.is_delete = data.is_delete
        }
        if(data.controlTemp){
            where.controlTemp = data.controlTemp
        }
        if(data.username){
            where.username = data.username
        }
        data._id = temp_db.ObjectID(data._id)
        let arr = await temp_db.updateOne('controlTemp', { _id:data._id }, { $set: where })
        pu.success('OK',data, res)
        return
    }


}

module.exports = new temp()
